import { useEffect, useState } from 'react';
import { getApiClient } from '@/lib/api';

interface WechatJSSDKConfig {
  appId: string;
  timestamp: number;
  nonceStr: string;
  signature: string;
}

interface ShareData {
  title: string;
  desc: string;
  link: string;
  imgUrl: string;
}

export const useWechatShare = (shareData: ShareData) => {
  const [isWechat, setIsWechat] = useState(false);
  const [config, setConfig] = useState<WechatJSSDKConfig | null>(null);
  const [isReady, setIsReady] = useState(false);

  // 检测是否在微信环境
  useEffect(() => {
    const ua = navigator.userAgent.toLowerCase();
    setIsWechat(ua.includes('micromessenger'));
  }, []);

  // 获取微信JS-SDK配置
  useEffect(() => {
    if (!isWechat) return;

    const getJSSDKConfig = async () => {
      try {
        const apiClient = getApiClient();
        const result = await apiClient.get(
          `/api/wechat/jssdk-config?url=${encodeURIComponent(window.location.href)}`
        ) as { success: boolean; data: WechatJSSDKConfig };
        
        if (result.success) {
          setConfig(result.data);
        }
      } catch (error) {
        console.error('获取微信JS-SDK配置失败:', error);
      }
    };

    getJSSDKConfig();
  }, [isWechat]);

  // 初始化微信JS-SDK
  useEffect(() => {
    if (!isWechat || !config || typeof window === 'undefined') return;

    const initWechatJSSDK = () => {
      // 动态加载微信JS-SDK
      const script = document.createElement('script');
      script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
      script.onload = () => {
        if (window.wx) {
          window.wx.config({
            debug: false,
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
          });

          window.wx.ready(() => {
            setIsReady(true);
            
            // 设置分享到朋友圈
            window.wx?.updateTimelineShareData({
              title: shareData.title,
              link: shareData.link,
              imgUrl: shareData.imgUrl,
              success: () => {
                console.log('分享到朋友圈设置成功');
              },
            });

            // 设置分享给朋友
            window.wx?.updateAppMessageShareData({
              title: shareData.title,
              desc: shareData.desc,
              link: shareData.link,
              imgUrl: shareData.imgUrl,
              success: () => {
                console.log('分享给朋友设置成功');
              },
            });
          });

          window.wx.error((res: unknown) => {
            console.error('微信JS-SDK配置失败:', res);
          });
        }
      };
      document.head.appendChild(script);
    };

    initWechatJSSDK();
  }, [config, shareData, isWechat]);

  return {
    isWechat,
    isReady,
  };
};
